package com.hae.shop.micoshopwechatservice.controller;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.RedisUtil;
import com.hae.shop.micoshopwechatservice.constant.BizErrorEnum;
import com.hae.shop.wechat.api.WechatService;
import com.hae.shop.wechat.model.respDto.AppInfoRespDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class WechatController implements WechatService {

    @Value("${hae.weixin.name}")
    private String name;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("getApp")
    public Response<AppInfoRespDto> getApp() {
        return new Response(new AppInfoRespDto("644064779", name));
    }

    @PostMapping("/varifyCode")
    @Override
    public Response<Boolean> verifyCode(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        Response response = new Response(Boolean.FALSE);

        // 验证验证码或手机号是否为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
            response.setErrorMsg(BizErrorEnum.MOBILE_OR_CODE_EMPTY.getErrorMsg());
            response.setErrorCode(BizErrorEnum.MOBILE_OR_CODE_EMPTY.getErrorCode());
        } else {
            // 验证码是否已失效
            String bmsCode = redisUtil.getString(Constants.WEIXINCODE_KEY + mobile);
            if (StringUtils.isEmpty(bmsCode)) {
                response.setErrorMsg(BizErrorEnum.BMS_CODE_EXPIRED.getErrorMsg());
                response.setErrorCode(BizErrorEnum.BMS_CODE_EXPIRED.getErrorCode());
            } else {
                // 验证码比对
                if (!bmsCode.equals(code)) {
                    response.setErrorMsg(BizErrorEnum.BMS_CODE_ERROR.getErrorMsg());
                    response.setErrorCode(BizErrorEnum.BMS_CODE_ERROR.getErrorCode());
                } else {
                    // 都满足时返回成功
                    response.setResult(Boolean.TRUE);
                }
            }
        }

        return response;
    }
}
